'''
第七周作业：python爬虫基础上
作业内容：有道翻译数据抓取
时间：20180908

使用示例：
------youdao('urllib','您好')
------youdao('requtsts','python')	
'''

from urllib import request,parse
import requests
import json
import hashlib
import time
import random

def youdao(action,msg):
	'''
	func_name : 有道翻译数据抓取
	@param : string action 抓取方式 requests.post urllib两种方式
	@param : string msg 等待翻译的数据信息
	@return : string info 翻译结果
	'''

	#定义url变量，
	_url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

	# 获取salt
	salt = str(int(time.time()*1000) + random.randint(1,10))
	u = 'fanyideskweb'        
	c = 'ebSeFb%=XZ%T[KZ)c(sy!'
	sign = hashlib.md5((u + msg + salt + c).encode('utf-8')).hexdigest()

	# 定义请求参数
	data = {
		'i':msg,
		'from':'AUTO',
		'to':'AUTO',
		'smartresult':'dict',
		'client':'fanyideskweb',
		'salt':salt,
		'sign':sign,
		'doctype':'json',
		'version':'2.1',
		'keyfrom':'fanyi.web',
		'action':'FY_BY_REALTIME',
		'typoResult':'false',
	}

	# 定义头信息
	headers = {
		'Accept':'application/json, text/javascript, */*; q=0.01',
		# 'Accept-Encoding':'gzip, deflate',
		'Accept-Language':'zh-CN,zh;q=0.9',
		'Connection':'keep-alive',
		# 'Content-Length':202,
		'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
		'Cookie':'OUTFOX_SEARCH_USER_ID=-965954771@10.168.8.64; JSESSIONID=aaa_OkXkIw8QF93NZbbxw; OUTFOX_SEARCH_USER_ID_NCOO=1593713896.2934394; fanyi-ad-id=49843; fanyi-ad-closed=1; UM_distinctid=165c107d14d3ab-05247e1676402c-5b193413-13c680-165c107d14e3bb; ___rl__test__cookies=1536542112392',
		'Host':'fanyi.youdao.com',
		'Origin':'http://fanyi.youdao.com',
		'Referer':'http://fanyi.youdao.com/',
		'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
		'X-Requested-With': 'XMLHttpRequest'
	}

	if action == 'request':

		# 发送请求，抓取信息
		res = requests.post(_url,data=data,headers=headers)

		# 解析结果并输出
		str_json = res.content.decode('utf-8') # 获取响应的json字串
		
	elif action == 'urllib':
		data = parse.urlencode(data) #编码转换
		# 发送请求，抓取信息
		req = request.Request(url=_url,data=bytes(data,encoding='utf-8'),headers=headers)
		res = request.urlopen(req)
		str_json = res.read().decode('utf-8') # 获取响应的json字串
		
	myjson = json.loads(str_json) # 把json转字典
	info = myjson['translateResult'][0][0]['tgt']
	print(info)
	


if __name__ == '__main__':
	_action = input("请输入操作方式,此处有两种选择urllib和request:")
	while True:
		keywords = input("请输入翻译内容：")
		if(keywords == 'q'):
			break
		youdao(_action,keywords)